using System;
using System.Collections.Generic;
using System.Reflection;
using iPhOwa.Exchange.Attributes;
using iPhOwa.Exchange.Exceptions;

namespace iPhOwa.Exchange.ContentClasses
{
	/// <summary>
	/// Creates items based on their content class.
	/// </summary>
	public static class ItemFactory
	{
		private static readonly Assembly assembly = Assembly.GetAssembly(typeof(Item));
		private static IDictionary<string, Type> itemTypes;

		private static IDictionary<string, Type> ItemTypes
		{
			get
			{
				if(itemTypes == null)
				{
					itemTypes = new Dictionary<string, Type>();

					IList<Type> types = assembly.GetTypes();

					foreach(Type t in types)
					{
						object[] atts = t.GetCustomAttributes(typeof(ExchangeContentClassAttribute), false);

						if(atts != null && atts.Length > 0)
						{
							itemTypes.Add(((ExchangeContentClassAttribute)atts[0]).FullName, t);
						}
					}
				}

				return itemTypes;
			}
		}

		/// <summary>
		/// Instantiates an <see cref="Item"/> based on it's content class.
		/// </summary>
		public static Item Create(string contentClass)
		{
			if(!ItemTypes.ContainsKey(contentClass))
			{
				throw new UnsupportedContentClassException();
			}

			return assembly.CreateInstance(itemTypes[contentClass].FullName) as Item;
		}
	}
}